﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using SBlogCore.Common.JWTExtend.Models;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SBlogCore.Common.JWTExtend.Helpers
{
    [SkipScan]
    public class JwtHelper
    {
        private static double? _expValue;
        /// <summary>
        /// 获取过期时间
        /// </summary>
        /// <returns></returns>
        private static double GetExp()
        {
            if (!_expValue.HasValue)
            {
                string exp = AppSetting.ReadAppSettings("Jwt:Exp");
                _expValue = double.Parse(exp);
            }
            return _expValue.Value;
        }

        /// <summary>
        /// 颁发JWT字符串
        /// </summary>
        /// <param name="tokenModel"></param>
        /// <param name="httpContextAccessor"></param>
        /// <returns></returns>
        public static TokenResultModel IssueJwt(TokenModelJwt tokenModel, IHttpContextAccessor httpContextAccessor)
        {
            string iss = AppSetting.ReadAppSettings("Jwt:Issuer");
            string aud = AppSetting.ReadAppSettings("Jwt:Audience");
            string secret = AppSetting.ReadAppSettings("Jwt:Secret");
            double expValue = GetExp();
            var claims = new List<Claim>
              {
                 /*
                 * 特别重要：
                   1、这里将用户的部分信息，比如 uid 存到了Claim 中，如果你想知道如何在其他地方将这个 uid从 Token 中取出来，请看下边的SerializeJwt() 方法，或者在整个解决方案，搜索这个方法，看哪里使用了！
                   2、你也可以研究下 HttpContext.User.Claims ，具体的你可以看看 Policys/PermissionHandler.cs 类中是如何使用的。
                 */                

                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                //这个就是过期时间，目前是过期1000秒，可自定义，注意JWT有自己的缓冲过期时间
                new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddSeconds(expValue)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Iss,iss),
                new Claim(JwtRegisteredClaimNames.Aud,aud),
                new Claim("IsAdmin",tokenModel.IsAdmin.ToString(),typeof(bool).ToString()),//自定义声明,是否为Admin
                new Claim("OrgId",tokenModel.OrgId.ToString() ?? string.Empty,typeof(long).ToString()),//自定义声明,组织ID
                new Claim("PlantId",tokenModel.PlantId.ToString() ?? string.Empty,typeof(long).ToString()),//自定义声明,组织ID
               };

            if (!string.IsNullOrEmpty(tokenModel.Role))
            {
                // 可以将一个用户的多个角色全部赋予；
                claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
            }
            //秘钥 (SymmetricSecurityKey 对安全性的要求，密钥的长度太短会报出异常)
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: iss,
                claims: claims,
                signingCredentials: cred);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);
            httpContextAccessor.HttpContext!.Response.Headers.Add("access-token", encodedJwt);
            return new TokenResultModel
            {
                token = encodedJwt,
                expires_in = expValue,
                token_type = "Bearer"
            };
        }

        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static TokenModelJwt SerializeJwt(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
            object role;
            try
            {
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role!);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            var claimDic = jwtToken.Claims.ToDictionary<Claim, string, object>(claim => claim.Type, claim => claim.Value);
            var tm = new TokenModelJwt
            {
                Uid = long.Parse(jwtToken.Id),
                Role = (role ?? "").ToString(),
                IsAdmin = bool.Parse(claimDic["IsAdmin"].ToString() ?? "False"),
                OrgId = !string.IsNullOrEmpty(claimDic["OrgId"].ToString()) ? long.Parse(claimDic["OrgId"].ToString()!) : null,
                PlantId = !string.IsNullOrEmpty(claimDic["PlantId"].ToString()) ? long.Parse(claimDic["PlantId"].ToString()!) : null,
            };
            return tm;
        }

        public static bool CustomSafeVerify(string token)
        {
            string secret = AppSetting.ReadAppSettings("Jwt:Secret");
            var jwtHandler = new JwtSecurityTokenHandler();
            var keyByteArray = Encoding.ASCII.GetBytes(secret);
            var signingKey = new SymmetricSecurityKey(keyByteArray);
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

            var jwt = jwtHandler.ReadJwtToken(token);
            return jwt.RawSignature == Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(jwt.RawHeader + "." + jwt.RawPayload, signingCredentials);
        }
    }
}
